package cn.dujc.superkid.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;

import cn.dujc.core.ui.BaseActivity;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.adapter.CupUnitTestAdapter;
import cn.dujc.superkid.adapter.UnitTestAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.CupExaminePageResult;
import cn.dujc.superkid.bean.ExamineListEntity;
import cn.dujc.superkid.bean.ExamineResultsResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.ResultsEntity;
import cn.dujc.superkid.bean.ScoreStatisticsEntity;
import cn.dujc.superkid.bean.UnitResult;
import cn.dujc.superkid.bean.UnitTestResult;
import cn.dujc.superkid.utils.Preferences;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/10/23 0023.
 */

public class CupUnitTest extends BaseActivity implements View.OnClickListener, UnitTestAdapter.OnItemViewClickListener {
    String examine_id;
    RecyclerView testRecycler, msgRecycler;
    CupUnitTestAdapter testAdapter;
    Chronometer chronometer;
    TextView tv_title;

    @Override
    public int getViewId() {
        return R.layout.activity_unittest;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        setTitle("考试");
        examine_id = getIntent().getStringExtra("examine_id");
        chronometer = findViewById(R.id.chronometer);
        chronometer = findViewById(R.id.chronometer);
        chronometer.setBase(SystemClock.elapsedRealtime());//计时器清零
        int hour = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000 / 60);
        chronometer.setFormat("0" + String.valueOf(hour) + ":%s");
        tv_title=findViewById(R.id.tv_title);
        testRecycler = findViewById(R.id.unit_test_recycler);
        testRecycler.setLayoutManager(new LinearLayoutManager(this));
        testAdapter = new CupUnitTestAdapter(this);
        testAdapter.setOnItemViewClickListener(this);
        testRecycler.setNestedScrollingEnabled(false);
        testRecycler.setAdapter(testAdapter);
        msgRecycler = findViewById(R.id.unit_test_mes_recycler);
        msgRecycler.setNestedScrollingEnabled(false);
        msgRecycler.setLayoutManager(new LinearLayoutManager(this));
        findViewById(R.id.bt_tijiao).setOnClickListener(this);
        findViewById(R.id.l_liuyan).setVisibility(View.GONE);
        loadData(0);
    }

    //    cupExamineResults
    private void loadData(final int type) {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(this);
        HttpHelper.getCupMatch().cupExaminePage(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(this).getChannel_id())
                .put("logincode", loginResult.getLogincode())
                .put("examine_id", examine_id)//试卷id
                .create()).enqueue(new Callback<Result<CupExaminePageResult>>() {
            @Override
            public void onResponse(Call<Result<CupExaminePageResult>> call, Response<Result<CupExaminePageResult>> response) {
                testAdapter.setList(response.body().getData().getExamine_list());
                tv_title.setText("共有"+response.body().getData().getExamine_num()+"道题目，考试时间为"+
                        response.body().getData().getEx_usedtime()+"分钟，共计"+response.body().getData().getEx_score()+"分");
                chronometer.start();
            }

            @Override
            public void onFailure(Call<Result<CupExaminePageResult>> call, Throwable t) {

            }
        });
    }

    private void submitTest() {
        for (int i = 0; i < testAdapter.getList().size(); i++) { //校验是否有题没填写答案
            if (TextUtils.isEmpty(testAdapter.getList().get(i).getValue())) {
                ToastUtil.showToast(this, "第" + (i + 1) + "题没答");
                return;
            }
        }
        requestSubmit();
    }

    private void requestSubmit() {
        ToastUtil.showToast(this, "正在提交数据");
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        QMap map = QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("examine_id", Integer.parseInt(examine_id))
                .put("logincode", loginResult.getLogincode())
                .put("answer", testAdapter.getValue())
                .put("when", chronometer.getText())
                .create();
        Log.e("qmap", new Gson().toJson(map));
        HttpHelper.getCupMatch().cupExamineResults(map).enqueue(new ResultCallBack<Result<ExamineResultsResult>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<ExamineResultsResult> body) {
                ArrayList<ResultsEntity> list = (ArrayList<ResultsEntity>) body.getData().getResults();
                ArrayList<ScoreStatisticsEntity> list1 = (ArrayList<ScoreStatisticsEntity>) body.getData().getScore_statistics();
                ArrayList<ExamineListEntity> testList = (ArrayList<ExamineListEntity>) testAdapter.getList();
                starter().with("unitResult", list)
                        .with("num", body.getData().getPage_info().getNum())
                        .with("first_score", "0")
                        .with("total_score", "0")
                        .with("title", body.getData().getPage_info().getExamine_title())
                        .with("statistics", list1)
                        .with("testList", testList)
                        .go(CupUnitTestResultActivity.class);
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bt_tijiao) {
            submitTest();
        }
    }

    @Override
    public void onItemViewClick(View v, int pos) {
        switch (v.getId()){
            case R.id.exercises_jiexi:
                Intent intent1=new Intent(this,ResolvtionActivity.class);
                intent1.putExtra("title", testAdapter.getList().get(pos).getProblem_title());
                intent1.putExtra("jiexi","");
                intent1.putExtra("daan",testAdapter.getList().get(pos).getCorrect_answer().get(0));
                startActivity(intent1);
                break;
        }
    }
}
